<template>
  <div class="koi-flex flex-row">
    <KoiCard class="max-w-200px m-r-6px">
      <template #header>
        <div class="flex flex-justify-between select-none">
          <div class="flex flex-items-center gap-6px">
            <el-icon :size="16">
              <Picture />
            </el-icon>
            <div class="text-15px">图片分类</div>
          </div>
        </div>
      </template>
      <div class="overflow-y-auto">
        <div
          class="h-34px text-14px text-#555 m-t-2px rounded-6px dark:text-#CFD3DC flex flex-items-center p-y-4px p-x-16px hover:bg-#F4F4F5 hover:dark:bg-[rgba(255,255,255,0.06)] border-1px border-solid border-transparent hover:border-[--el-border-color-light]"
          v-for="item in koiDicts.sys_picture_type"
          :key="item.dictId"
          :class="
            selectedIndex === item?.dictValue
              ? 'bg-[--el-color-primary-light-9]! text-[--el-color-primary]! border-[--el-color-primary-light-7]!'
              : ''
          "
          @click="handleSelectedIndex(item?.dictValue)"
        >
          <div class="line-clamp-1">{{ item.dictLabel }}</div>
        </div>
      </div>
    </KoiCard>
    <div class="koi-flex">
      <KoiSearch :isFold="true" :showSearch="showSearch">
        <!-- 搜索条件 -->
        <el-form :inline="true">
          <el-form-item label="图片后缀" prop="pictureSuffix">
            <el-input
              placeholder="请输入图片后缀"
              v-model="searchParams.pictureSuffix"
              clearable
              style="width: 220px"
              @keyup.enter.native="handleListPage"
            ></el-input>
          </el-form-item>
          <el-form-item label="服务类型" prop="pictureService">
            <el-select
              placeholder="请选择图片服务类型"
              v-model="searchParams.pictureService"
              clearable
              style="width: 220px"
              @keyup.enter.native="handleListPage"
            >
              <el-option
                v-for="koi in koiDicts.sys_file_service"
                :key="koi.dictValue"
                :label="koi.dictLabel"
                :value="koi.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="search" plain @click="handleSearch" v-auth="['system:picture:search']">{{
              $t("button.search")
            }}</el-button>
            <el-button type="danger" icon="refresh" plain @click="resetSearch">{{ $t("button.reset") }}</el-button>
          </el-form-item>
        </el-form>
      </KoiSearch>
      <KoiCard>
        <!-- 表格头部按钮 -->
        <el-row :gutter="10">
          <el-col :span="1.5" v-auth="['system:picture:upload']">
            <el-button type="primary" icon="Upload" plain @click="handleUpload()">{{ $t("button.picture") }}</el-button>
          </el-col>
          <el-col :span="1.5" v-auth="['system:picture:delete']">
            <el-button type="danger" icon="delete" plain @click="handleBatchDelete()" :disabled="multiple">{{
              $t("button.delete")
            }}</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" icon="Switch" plain @click="handleSwitch()">切换</el-button>
          </el-col>
          <KoiToolbar v-model:showSearch="showSearch" @refreshTable="handleListPage"></KoiToolbar>
        </el-row>

        <div class="h-20px"></div>
        <!-- 图库展示 -->
        <div class="koi-flex flex-row flex-wrap flex-content-start overflow-y-auto" v-show="isSwitch">
          <div
            v-if="tableList.length > 0"
            class="pos-relative flex flex-justify-center flex-items-center w-160px h-220px m-y-5px m-r-8px border-rounded border-solid border-1px border-[--el-border-color-light] hover:shadow-[--el-box-shadow-light] bg-[rgba(50,50,50,0.06)] dark:bg-[rgba(255,255,255,0.06)]"
            v-for="item in tableList"
            :key="item.pictureId"
          >
            <el-image
              class="w-156px h-156px"
              fit="contain"
              :preview-teleported="true"
              :preview-src-list="[item.picturePath]"
              :src="item.picturePath"
            >
              <template #error>
                <el-image
                  src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
                  fit="cover"
                  :preview-src-list="['https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png']"
                  :preview-teleported="true"
                  class="w-156px h-156px"
                ></el-image>
              </template>
            </el-image>
            <!-- 选择图片 -->
            <div class="pos-absolute right-2px top-2px max-w-100px text-16px">
              <el-checkbox
                size="small"
                :key="item.pictureId"
                :value="item.pictureId"
                label="选择"
                border
                @change="handlePictureCheckBox($event, item.pictureId)"
              />
            </div>
            <!-- 图片下载/详情/删除 -->
            <div class="pos-absolute right-0 bottom-0 max-w-100px text-16px m-r-4px m-b-2px flex select-none">
              <el-tooltip content="删除文件" placement="top">
                <div
                  class="m-r-2px hover:text-[--el-color-primary] hover:bg-[rgba(0,0,0,0.06)] rounded hover:dark:bg-[rgba(255,255,255,0.06)]"
                  @click="handleDelete(item)"
                >
                  <el-icon class="m-4px"><Delete /></el-icon>
                </div>
              </el-tooltip>

              <el-tooltip placement="top">
                <template #content>
                  <div class="w-260px text-12px">
                    <div>原名称：{{ item.pictureName }}</div>
                    <div>新名称：{{ item.newName }}</div>
                    <div>文件大小：{{ item.pictureSize }}</div>
                    <div>上传路径：{{ item.pictureUpload }}</div>
                    <div>回显路径：{{ item.picturePath }}</div>
                    <div>
                      服务类型：{{
                        item.pictureService == "1"
                          ? "本地存储"
                          : item.pictureService == "2"
                            ? "MINIO"
                            : item.pictureService == "3"
                              ? "OSS"
                              : "其他"
                      }}
                    </div>
                  </div>
                </template>
                <div
                  class="m-r-2px hover:text-[--el-color-primary] hover:bg-[rgba(0,0,0,0.06)] rounded hover:dark:bg-[rgba(255,255,255,0.06)]"
                >
                  <el-icon class="m-4px"><Warning /></el-icon>
                </div>
              </el-tooltip>
              <el-tooltip content="下载文件" placement="top">
                <div
                  class="hover:text-[--el-color-primary] hover:bg-[rgba(0,0,0,0.06)] rounded hover:dark:bg-[rgba(255,255,255,0.06)]"
                  @click="handleDownload(item)"
                >
                  <el-icon class="m-4px"><Download /></el-icon>
                </div>
              </el-tooltip>
            </div>
          </div>
          <div v-else class="w-100% h-100%">
            <el-empty :image="errorUrl" :image-size="360" description="主人，没有数据了哟👻"></el-empty>
          </div>
        </div>
        <!-- 数据表格 -->
        <el-table
          v-show="!isSwitch"
          v-loading="loading"
          border
          :data="tableList"
          empty-text="暂时没有数据哟"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" prop="pictureId" width="70px" align="center" type="index"></el-table-column>
          <el-table-column
            label="图片原始名称"
            prop="pictureName"
            width="120px"
            align="center"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column
            label="图片新名称"
            prop="newName"
            width="220px"
            align="center"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column label="图片类型" prop="pictureType" width="100px" align="center">
            <template #default="scope">
              <KoiTag :tagOptions="koiDicts.sys_picture_type" :value="scope.row.pictureType"></KoiTag>
            </template>
          </el-table-column>
          <el-table-column
            label="图片大小"
            prop="pictureSize"
            width="120px"
            align="center"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column
            label="图片后缀"
            prop="pictureSuffix"
            width="120px"
            align="center"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column
            label="图片上传路径"
            prop="pictureUpload"
            width="120px"
            align="center"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column label="图片回显路径" prop="picturePath" width="120px" align="center" :show-overflow-tooltip="true">
            <template #default="scope">
              <el-tooltip :content="scope.row.picturePath" placement="top">
                <div class="flex flex-justify-center">
                  <el-image
                    class="rounded-8px w-60px h-60px"
                    fit="contain"
                    :preview-teleported="true"
                    :preview-src-list="[scope.row.picturePath]"
                    :src="scope.row.picturePath"
                  >
                    <template #error>
                      <el-image
                        src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
                        fit="cover"
                        :preview-src-list="['https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png']"
                        :preview-teleported="true"
                        class="w-60px h-60px rounded-8px"
                      ></el-image>
                    </template>
                  </el-image>
                </div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="服务类型" prop="pictureService" width="100px" align="center">
            <template #default="scope">
              <KoiTag :tagOptions="koiDicts.sys_file_service" :value="scope.row.pictureService"></KoiTag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createTime" width="180px" align="center"></el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="110"
            fixed="right"
            v-auth="['system:picture:download', 'system:picture:delete']"
          >
            <template #default="{ row }">
              <el-tooltip content="图片下载" placement="top">
                <el-button
                  type="info"
                  icon="Download"
                  circle
                  plain
                  @click="handleDownload(row)"
                  v-auth="['system:picture:download']"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button
                  type="danger"
                  icon="Delete"
                  circle
                  plain
                  @click="handleDelete(row)"
                  v-auth="['system:picture:delete']"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <div class="h-20px"></div>
        <!-- 分页 -->
        <el-pagination
          background
          v-model:current-page="searchParams.pageNo"
          v-model:page-size="searchParams.pageSize"
          v-show="total > 0"
          :page-sizes="[10, 20, 50, 100, 200]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleListPage"
          @current-change="handleListPage"
        />

        <!-- 多文件/单文件上传 -->
        <KoiDialog ref="koiDialogRef" :title="title" :footerHidden="true" :height="330">
          <template #content>
            <el-form ref="formRef" :rules="rules" :model="form" label-width="auto" status-icon>
              <el-row :gutter="10">
                <el-col :xs="{ span: 12 }" :sm="{ span: 12 }">
                  <el-form-item label="服务类型" prop="pictureService">
                    <el-select
                      placeholder="请选择服务类型"
                      v-model="form.pictureService"
                      clearable
                      style="width: 220px"
                      @change="handlePictureServiceChange"
                    >
                      <el-option
                        v-for="koi in koiDicts.sys_file_service"
                        :key="koi.dictValue"
                        :label="koi.dictLabel"
                        :value="koi.dictValue"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="{ span: 12 }" :sm="{ span: 12 }">
                  <el-form-item label="图片类型" prop="pictureType">
                    <el-select placeholder="请选择图片类型" v-model="form.pictureType" clearable style="width: 220px">
                      <el-option
                        v-for="koi in koiDicts.sys_picture_type"
                        v-show="koi.dictValue !== '0'"
                        :key="koi.dictValue"
                        :label="koi.dictLabel"
                        :value="koi.dictValue"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                  <el-form-item label="文件回显路径" prop="picturePath">
                    <KoiUploadImages
                      v-model:fileList="form.picturePath"
                      :fileParam="form.pictureType"
                      folderName="pictures"
                    >
                    <template #content>
                      <el-icon>
                        <Picture />
                      </el-icon>
                      <span>请上传图片</span>
                    </template>
                  </KoiUploadImages>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </template>
        </KoiDialog>
      </KoiCard>
    </div>
  </div>
</template>

<script setup lang="ts" name="picturePage">
import { nextTick, ref, reactive, onMounted } from "vue";
import errorUrl from "@/assets/images/error/404.png";
import { koiNoticeSuccess, koiNoticeError, koiMsgError, koiMsgWarning, koiMsgBox, koiMsgInfo } from "@/utils/koi.ts";
import { listPage, deleteById, batchDelete } from "@/api/system/picture/index.ts";
import { useKoiDict } from "@/hooks/dicts/index.ts";

const { koiDicts } = useKoiDict(["sys_picture_type", "sys_file_service"]);
// 表格加载动画Loading
const loading = ref(false);
// 是否显示搜索表单[默认显示]
const showSearch = ref<boolean>(true);
// 表格数据
const tableList = ref<any>([]);

// 查询参数
const searchParams = ref<any>({
  pageNo: 1, // 第几页
  pageSize: 10, // 每页显示多少条
  pictureSuffix: "",
  pictureService: ""
});

const total = ref<number>(0);

/** 重置搜索参数 */
const resetSearchParams = () => {
  searchParams.value = {
    pageNo: 1,
    pageSize: 10,
    pictureType: selectedIndex.value,
    pictureSuffix: "",
    pictureService: ""
  };
};

/** 搜索 */
const handleSearch = () => {
  searchParams.value.pageNo = 1;
  handleTableData();
};

/** 重置 */
const resetSearch = () => {
  resetSearchParams();
  handleListPage();
};

/** 数据表格 */
const handleListPage = async () => {
  try {
    tableList.value = []; // 重置表格数据
    loading.value = true;
    const res: any = await listPage(searchParams.value);
    tableList.value = res.data.records;
    total.value = res.data.total;
    loading.value = false;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试");
  }
};

/** 数据表格[不带Loading，删除、批量删除等使用] */
const handleTableData = async () => {
  try {
    const res: any = await listPage(searchParams.value);
    tableList.value = res.data.records;
    total.value = res.data.total;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试");
  }
};

// 获取表格数据
onMounted(() => {
  handleListPage();
});

const ids = ref<any>([]); // 选择数组
const single = ref<boolean>(true); // 非单个禁用
const multiple = ref<boolean>(true); // 非多个禁用

/** 是否多选 */
const handleSelectionChange = (selection: any) => {
  ids.value = selection.map((item: any) => item.pictureId);
  single.value = selection.length != 1; // 单选
  multiple.value = !selection.length; // 多选
};

/** 删除 */
const handleDelete = (row: any) => {
  const id = row.pictureId;
  if (id == null || id == "") {
    koiMsgWarning("请选择需要删除的数据");
    return;
  }
  koiMsgBox("您确认删除该数据么？删除后将无法进行恢复？")
    .then(async () => {
      try {
        await deleteById(id);
        handleTableData();
        koiNoticeSuccess("删除成功");
      } catch (error) {
        console.log(error);
        handleTableData();
        koiNoticeError("删除失败，请刷新重试");
      }
    })
    .catch(() => {
      koiMsgError("已取消");
    });
};

/** 批量删除 */
const handleBatchDelete = () => {
  if (ids.value.length == 0) {
    koiMsgInfo("请选择需要删除的数据");
    return;
  }
  koiMsgBox("您确认进行批量删除么？删除后将无法进行恢复？")
    .then(async () => {
      try {
        await batchDelete(ids.value);
        handleTableData();
        koiNoticeSuccess("批量删除成功");
      } catch (error) {
        console.log(error);
        handleTableData();
        koiNoticeError("批量删除失败，请刷新重试");
      }
    })
    .catch(() => {
      koiMsgError("已取消");
    });
};

// 选择颜色
const selectedIndex = ref("0");

/** 点击选择分类 */
const handleSelectedIndex = (value?: string) => {
  if (value) {
    selectedIndex.value = value;
    searchParams.value.pictureType = selectedIndex.value;
    handleListPage();
  }
};

/** 图片上传 */
const handleUpload = () => {
  // 打开对话框
  koiDialogRef.value.koiOpen();
  koiMsgInfo("上传图片");
  // 标题
  title.value = "上传操作";
  // 重置表单
  resetForm();
  form.value.filePath = [];
};

// 多文件/单文件上传对话框
const koiDialogRef = ref();
// 标题
const title = ref("图库表");
// form表单Ref
const formRef = ref<any>();

// form表单
let form = ref<any>({
  picturePath: [],
  pictureService: "1",
  pictureType: "9"
});

/** 清空表单数据 */
const resetForm = () => {
  // 等待 DOM 更新完成
  nextTick(() => {
    if (formRef.value) {
      // 重置该表单项，将其值重置为初始值，并移除校验结果
      formRef.value.resetFields();
    }
  });
  form.value = {
    picturePath: [],
    pictureService: "1",
    pictureType: "9"
  };
};

/** 表单规则 */
const rules = reactive({
  picturePath: [{ required: true, message: "请上传图片", trigger: "blur" }],
  pictureService: [{ required: true, message: "请选择服务类型", trigger: "blur" }],
  pictureType: [{ required: true, message: "请选择图片类型", trigger: "blur" }]
});

/** 选择类型改变 */
const handlePictureServiceChange = () => {
  // 其他服务类型，定义变量，改变组件上传路径接口
  if (form.value.pictureService !== "1") {
    koiMsgWarning("亲，暂时仅支持本地上传哟");
  }
};

/** 文件下载 */
const handleDownload = (row: any) => {
  const fileOriginalName = row?.pictureName;
  const url = row?.picturePath;
  if (url == null || url == "") {
    koiMsgWarning("请选择需要下载的数据");
    return;
  }
  koiMsgBox("您确认下载该数据么？")
    .then(async () => {
      try {
        const response = await fetch(url);
        if (!response.ok) {
          throw new Error(`Network response was not ok: ${response.status}`);
        }
        // 创建 Blob 对象
        const blob = await response.blob();
        // 创建对象 URL
        const downloadUrl = window.URL.createObjectURL(blob);
        // 创建一个隐藏的下载链接
        const link = document.createElement("a");
        link.href = downloadUrl;
        link.download = fileOriginalName; // 设置下载文件名
        link.style.display = "none";
        // 添加到 DOM 中
        document.body.appendChild(link);
        // 触发点击事件
        link.click();
        // 清理
        document.body.removeChild(link);
        window.URL.revokeObjectURL(downloadUrl);
        koiNoticeSuccess("下载成功");
      } catch (error) {
        console.log(error);
        handleTableData();
        koiNoticeError("下载失败，请刷新重试");
      }
    })
    .catch(() => {
      koiMsgError("已取消");
    });
};

/** 切换 */
const isSwitch = ref(false);
const handleSwitch = () => {
  multiple.value = !ids.value.length;
  isSwitch.value = !isSwitch.value;
};

/** 选择图片 */
const handlePictureCheckBox = (event: any, id: any) => {
  if (event === true) {
    // 添加
    ids.value.push(id);
  } else {
    // 移除包含ID的数据
    // 当 event 不为 true 时，使用 filter 方法创建一个新的数组，其中不包含与 id 相等的元素。然后将 pictureCheckBoxList 设置为这个新数组。
    ids.value = ids.value.filter((item: any) => item !== id);
  }
  multiple.value = !ids.value.length;
};
</script>

<style lang="scss" scoped></style>
